import {createSlice} from '@reduxjs/toolkit'
import React from 'react'
import {tranformMenu,tranformRoute} from '../../utils/menuUtil'
import {lazy} from 'react'
import lazyComponent from '../../utils/lazyComponent'
import storage from '../../utils/storeUtils'
const Login=lazy(()=>import('../../views/Login'))
const Layout=lazy(()=>import('../../views/Layout'))
const NotFound=lazy(()=>import('../../views/NotFound'))
import {DEFAULTSELECTKEYS,DEFAULTOPENKEYS} from '../../config/constant'

const menuSlice=createSlice({
    name:'menuNS',
    initialState:{
        menuItems:[],
        routes:[
            {
                path:'/login',
                element:lazyComponent(<Login></Login>)
            },
            {
                path:'/',
                element:lazyComponent(<Layout></Layout>)
            },
            {
                path:'*',
                element:lazyComponent(<NotFound></NotFound>)
            }
        ],
        isCollapsed:false,
        defaultOpenKeys:storage.getStorage(DEFAULTOPENKEYS)||['/home'],
        defaultSelectedKeys:storage.getStorage(DEFAULTSELECTKEYS)||['/home']
    },
    reducers:{
        SET_MENU_ITEMS(state,action){
            if(state.menuItems.length===0){
                state.menuItems=action.payload  
            }
        },
        SET_Collapsed(state,action){
          state.isCollapsed=action.payload
        },
        SET_ROUTES(state,action){
          if(!state.routes[1].children){
            state.routes[1].children=action.payload
          }
        },
        SET_DEFAULTOPEKEYS(state,action){
           
            state.defaultOpenKeys=action.payload
            storage.setStorage(DEFAULTOPENKEYS,action.payload)
        },
        SET_DEFAULTSELECTKEYS(state,action){
            const ary=[]
            state.defaultSelectedKeys=ary.push(action.payload)
            storage.setStorage(DEFAULTSELECTKEYS,ary)
        }
    }
})
export const getAuthMenuAsync=async(dispatch,getState)=>{
    const result=await React.$api.admin.getAuthMenusApi(getState().adminModule.user.username)
        
    console.log(result);
    const antdMenuList=tranformMenu(result[0].children.filter(item=>item.path!='/profile'))
    //将后端的菜单数组转成React-router-dom6版本的路由格式
    const distAry=[]
    tranformRoute(result[0].children,distAry)
    dispatch(SET_MENU_ITEMS(antdMenuList))
    dispatch(SET_ROUTES(distAry))
}
export const {SET_MENU_ITEMS,SET_Collapsed,SET_ROUTES,SET_STATUS,SET_DEFAULTOPEKEYS,SET_DEFAULTSELECTKEYS}=menuSlice.actions
export default menuSlice.reducer